define(function() {
    'use strict';
    class List{
        constructor(ops){
            this.cont = ops.cont;
            this.url = ops.url;

            this.load()
            this.addEvent();
        }
        load(){
            // console.log($)
            $.ajax({
                url:this.url
            }).then(data => {
                // console.log(data)
                this.data = JSON.parse(data)
                this.render();
            })
        }
        render(){
            let str = '';
            this.data.forEach(val => {
                str += `<div class="box" index="${val.proId}">
                        <img src="${val.proImg}" alt="">
                        <p class="price">${val.price}</p>
                        <p class="proName">${val.proName}</p>
                        <span class="btn">加入购物车</span>
                    </div>`
            });
            this.cont.html(str)
        }
        addEvent(){
            const that = this;
            this.cont.on("click", ".btn", function(){
                that.id = $(this).parent().attr("index");
                that.price = $(this).parent().children(".price").html();
                that.setData();
            })
        }
        setData(){
            const arr = localStorage.getItem("proData") ? JSON.parse(localStorage.getItem("proData")) : [];
    
            if(arr.length > 0){
                // 不是第一次，判断商品新旧
                let i = 0;
                const onoff = arr.some((val,idx)=>{
                    i = idx;
                    // 当some的回调函数返回true时，立即结束，并返回true
                    return val.id === this.id
                })
                if(onoff){
                    // 找到了，旧，修改数量
                    arr[i].num++
                }else{
                    // 没有找到，新，直接加
                    arr.push({
                        id:this.id,
                        num:1,
                        price:this.price,
                        flag:true
                    })
                }
            }else{
                // 第一次加入购物车，直接加
                arr.push({
                    id:this.id,
                    num:1,
                    price:this.price,
                    flag:true
                })
            }
            localStorage.setItem("proData", JSON.stringify(arr))
        }
    }
    return List;
});